package com.hk.newsservice.controller;

import com.github.pagehelper.PageInfo;
import com.hk.commons.CommonResult;
import com.hk.model.News;
import com.hk.model.vo.Result;
import com.hk.model.vo.ResultVO;
import com.hk.newsservice.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/7 9:08
 * @Statement: 新闻
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @GetMapping("/findAll")
    public ResultVO<News> findAll(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10")Integer limit,
            News news
    ) {
        List<News> newsList = newsService.findAll(page, limit, news);
        PageInfo<News> newsPageInfo = new PageInfo<>(newsList);
        int count = newsService.count(1,0, news);
        if (newsList.isEmpty()) {
            ResultVO resultVO = CommonResult.nullResultVO(count,newsPageInfo.getList());
            return resultVO;
        }
        ResultVO resultVO = CommonResult.successResultVO(count,newsPageInfo.getList());
        return resultVO;
//        return null;
    }

    @PostMapping("/save")
    public Result save(@RequestBody(required = false) News news) {
        if (news == null) {
            Result result = CommonResult.nullResult(null);
            return result;
        }
        newsService.save(news);
        Result result = CommonResult.successResult(null);
        return result;
//        return null;
    }

    @GetMapping("/findById/{id}")
    public Result findById(@PathVariable int id) {
        News news = newsService.findById(id);
        if (news.getId() == 0) {
            Result result = CommonResult.nullResult(null);
            return result;
        }
        Result result = CommonResult.successResult(news);
        return result;
//        return null;
    }

    @PostMapping("/updateMessage")
    public Result updateMessage(@RequestBody(required = false) News news) throws IOException {
        if (news == null) {
            Result result = CommonResult.nullResult(null);
            return result;
        }
        newsService.update(news);
        Result result = CommonResult.successResult(null);
        return result;
    }

    /**
     * 通过Id删除对应新闻信息
     * @param id
     * @return
     */
    @PostMapping("/deletetNews/{id}")
    public Result deletetNews(@PathVariable int id) throws IOException {
        newsService.delete(id);
        Result result = CommonResult.successResult(null);
        return result;
    }


}
